import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { staticRoutes, allAsyncRoutes, anyRouters } from "@/router/routes";
import { reqLogin, reqUserInfo } from "@/api/user";
import { RouteRecordRaw } from "vue-router";
import router from "@/router";

// 封装获取动态路由
function filterRouters(allAsyncRoutes: RouteRecordRaw[], routes: string[]) {
  return allAsyncRoutes.filter((item) => {
    if (routes.includes(item.name as string)) {
      //递归 过滤深层次的层级
      if (item.children && item.children.length > 0) {
        item.children = filterRouters(item.children!, routes);
      }
      return true;
    }
  });
}

// 封装路由映射
function addRoutes(routes: RouteRecordRaw[]) {
  routes.forEach((item) => router.addRoute(item));
}

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: "",
      avatar: "",
    },
    menuRoutes: [],
  }),

  actions: {
    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     */
    async login(username: string, password: string) {
      try {
        const res = await reqLogin({ username, password });
        this.token = res;
        setToken(res);
        // console.log(res);
      } catch (error: any) {
        ElMessage.error("登录失败:" + error.message);
      }
    },

    /**
     * 获取去用户信息
     */
    async getInfo() {
      try {
        const res = await reqUserInfo();
        this.userInfo = res;
        console.log(res);
        // const route = filterRouters(allAsyncRoutes, this.userInfo.routes);
        // console.log(route);

        // addRoutes(route);
        // this.menuRoutes = [...staticRoutes, ...route, ...anyRouters];
        this.menuRoutes = [...staticRoutes, ...allAsyncRoutes, ...anyRouters];
      } catch (error: any) {
        ElMessage.error("获取用户信息失败:" + error.message);
      }
      // return new Promise((resolve) => {
      //   setTimeout(() => {
      //     this.userInfo.name = "admin";
      //     this.userInfo.avatar =
      //       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
      //     this.menuRoutes = [...staticRoutes, ...allAsyncRoutes, ...anyRouters];
      //     resolve({
      //       name: this.userInfo.name,
      //       avatar: this.userInfo.avatar,
      //       token: this.token,
      //     });
      //   }, 1000);
      // });
    },

    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.userInfo.name = "";
      this.userInfo.avatar = "";
      window.location.reload();
    },
  },
});
